/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.news.server.speed;

import cn.ac.iie.di.commons.speeder.SpeedLimitTokenBucket;
import org.apache.log4j.Logger;

/**
 *
 * @author zwlin
 */
public class TotalSpeedLimiter implements SpeedLimiter {

	private static final Logger logger = Logger.getLogger(TotalSpeedLimiter.class);

	private SpeedLimitTokenBucket tokenBucket;
	private boolean activated;

	public TotalSpeedLimiter(int speedPerSec) {
		this.tokenBucket = new SpeedLimitTokenBucket(speedPerSec, 1, speedPerSec);
		this.activated = false;
	}

	@Override
	public boolean tryGetThrough(String key) {
		if (!activated) {
			logger.warn("TotalSpeedLimitor stopped.");
			return false;
		} else {
			return activated && tokenBucket.TryGetToken();
		}
	}

	@Override
	public void waitGetThrough(String key) {
		if (!activated) {
			logger.warn("TotalSpeedLimitor stopped.");
			return;
		} else {
			while (activated && !tokenBucket.GetToken());
			return;
		}
	}

	@Override
	public void start() {
		if (!activated) {
			synchronized (this) {
				if (!activated) {
					tokenBucket.start();
					this.activated = true;
				}
			}
		}
	}

	@Override
	public void stop() {
		if (activated) {
			synchronized (this) {
				if (activated) {
					this.activated = false;
					tokenBucket.stop();
				}
			}
		}
	}

	@Override
	public boolean isActivated() {
		return activated;
	}

}
